<?php


class ScreenAction extends Action{
	function add() {
		if ($_REQUEST['sign'] != D('Order')->encrypt($_REQUEST['id'])) {
			echo json_encode(-1);
			return false;
		}
		$imgData = $_POST['data'];
		$imgData = substr($imgData, 22);
		$imgData = base64_decode($imgData);
		$fileName = uniqid(dechex(time())).'.jpg';
		$filePath = "images/$fileName";
		/*$im = imagecreatefromstring($imgData);
		if ($im !== false) {
			imagejpeg($im,$filePath);
			imagedestroy($im);
		}*/
		
		$ret = 0;
		if(file_put_contents($filePath, $imgData)){
			$data = array(
				'scr_datetime'	=>	time(),
				'scr_file'	=>	$fileName,
				'ord_id'	=>	$_REQUEST['id']
			);
			$model = D('Screen');
			$id = $model->add($data);
			if (!$id) {
				$ret = -3;
				//echo $model->getError(),$model->getDbError();
			}else {
				$ret = $id;
			}
		}else {
			$ret = -2;
		}
		echo json_encode($ret);
	}
	
	function show() {
		$etag = $_REQUEST['id'];
		$time = time();
		$expire = 3600*24*5;//最多看5天的数据
		
		if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $etag == $_SERVER['HTTP_IF_NONE_MATCH']) {
			$this->header ( $etag, $time, $expire ,304);
			return TRUE;
		}
		
		$data = D('Screen')->find($_REQUEST['id']);
		if (!$data or $data['scr_datetime']<$time-$expire 
		or ($_REQUEST['sign']!=D('Order')->encrypt($data['ord_id']) and empty($_GET['lukeqin']))//签名要正确
		) {
			return false;
		}
		
		$data = substr($data['scr_data'], 22);
		$data = base64_decode($data);
		
		$im = imagecreatefromstring($data);
		if ($im !== false) {
			
			$this->header ( $etag, $time, $expire );

			imagejpeg($im);
			imagedestroy($im);
		}
		else {
			echo 'An error occurred.';
		}
		
	}
	
	private function header($etag, $time, $expire,$code='') {
		header("Cache-control: max-age=".$expire);
		if($code){
			header('Etag:' . $etag);
		}else{
			header('Etag:' . $etag, true, 304);
		}
		//header('Cache-Control: no-store, no-cache, must-revalidate');
		header("Expires: " . gmdate("D, d M Y H:i:s",$time+$expire) . "GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s",$time) . "GMT");
		header('Content-Type: image/jpeg');
	}

}
